package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiSyncDemo* @Description:系统API接口开发Demo ，重点关注业务逻辑部分
 * @author: LiJuntao* @date 2021-07-13 23:58:55
 *
 */

public class apiWXMiniPCode implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXMiniPCode.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        net.sf.json.JSONObject result = new net.sf.json.JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        //解析Json
        JSONObject inJson = null;
        try {
            inJson = new JSONObject(inData);
        } catch (Exception e) {
            log.error("系统接收到参数解析异常-", e);
            result.put("errcode", -1);
            result.put("errmsg", "系统接收到参数解析异常[" + e.getMessage() + "]");
            return result.toString();
        }
        String code = KHUtil.GetJV(inJson, "code");
        String opsource = KHUtil.GetJV(inJson, "opsource");
        String expand = KHUtil.GetJV(inJson, "expand");
        log.debug("回调参数信息【code】：" + code + "【opsource】：" + opsource + "【expand】：" + expand);

        // 调用微信获取OPENID
        String APPID = KHDBConfig.getParam(eliteBean, opsource + "-ID");
        String APPSECRET = KHDBConfig.getParam(eliteBean, opsource + "-KE");
        log.debug("获取到的微信公众号配置信息【APPID】：" + APPID + "【APPSECRET】：" + APPSECRET);

        // 通过Code信息获取openid
        if (!KHUtil.isNull(APPID)) {

            try {
                JSONObject apiTokenJson = new JSONObject(Util.doHttpGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + code + "&grant_type=authorization_code", "UTF-8", 5000, 0));

                log.debug("腾讯返回调用信息：" + apiTokenJson.toString());

                String errcode = KHUtil.GetJV(apiTokenJson, "errcode");//错误码
                String errmsg = KHUtil.GetJV(apiTokenJson, "errmsg");//错误信息
                String openid = KHUtil.GetJV(apiTokenJson, "openid");//用户唯一标识
                String session_key = KHUtil.GetJV(apiTokenJson, "session_key");//会话密钥
                String unionid = KHUtil.GetJV(apiTokenJson, "unionid");//用户在开放平台的唯一标识符

                result.put("errcode", errcode);
                result.put("errmsg", errmsg);
                result.put("openid", openid);
                result.put("login_key", openid);

                log.debug("获取到的微信用户信息：" + result.toString());
            } catch (Exception e1) {
                log.error("获取用户OpenID异常-", e1);
                result.put("errcode", -1);
                result.put("errmsg", "数据处理错误,请检查确认入参有效且合法");
            }
        } else {
            log.warn("获取到异常的公众号APPID警告:" + APPID);
            result.put("errcode", -1);
            result.put("errmsg", "调用参数异常,请检查确认入参有效且合法");
        }
        return result.toString();
    }
}